package net.dgg.zz.common.utils;

import net.dgg.zz.common.excption.CommonExcption;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 验证类
 * @Author:HDC
 * @Date: Created in 2018/5/31 19:17
 */
public class ValidateUtils {

    /**
     * 构造异常
     * @param exceptionClass
     * @param msg
     * @param <T>
     * @return
     */
    private static <T extends RuntimeException> T constructException(Class<T> exceptionClass,String msg){
        T exception= null;

        Constructor constructor= null;
        try {
            constructor = exceptionClass.getConstructor(String.class);
        } catch (NoSuchMethodException e) {
            throw new CommonExcption("缺少String为参数的构造函数",e);
        }
        try {
            exception = (T) constructor.newInstance(msg);
        } catch (InstantiationException e) {
            throw new CommonExcption(e.getMessage(),e);
        } catch (IllegalAccessException e) {
            throw new CommonExcption(e.getMessage(),e);
        } catch (InvocationTargetException e) {
            throw new CommonExcption(e.getMessage(),e);
        }

        return exception;
    }

    /**
     * 字符串不可为空的校验
     * @param data 被校验的对象
     * @param exceptionClass 抛出的异常类型，为空时则不抛出异常
     * @param msg 异常时的报错信息，如果为null，则为默认信息
     * @param <T>异常类型必须是RuntimeException的派生类
     */
    public static <T extends RuntimeException> boolean strNotEmpty(Object data,Class<T> exceptionClass,String msg){
        if(net.dgg.zz.common.utils.StringUtils.isEmpty(data)){
            if(exceptionClass!=null) {
                throw constructException(exceptionClass, msg == null ? "内容不可为空" : msg);
            }else{
                return false;
            }
        }else{
            return true;
        }
    }


    /**
     * 验证 true 或者 false
     * @param expression 被校验的 boolean 表达式
     * @param exceptionClass 抛出的异常类型，为true则不抛出异常
     * @param msg 异常时的报错信息，如果为null，则为默认信息
     * @param <T>异常类型必须是RuntimeException的派生类
     */
    public static <T extends RuntimeException> boolean isTrue(boolean expression,Class<T> exceptionClass,String msg){
        if (!expression) {
            throw constructException(exceptionClass, msg == null ? "验证不通过" : msg);
        }else {
            return true;
        }
    }
}
